
import 'package:flutter/material.dart';
import 'dart:io';
import 'dart:async';
import 'dart:convert';

class ServerMode extends StatefulWidget{
  const ServerMode({super.key});
  @override
  State<ServerMode> createState() => StServerMode();
}

class StServerMode extends State<ServerMode> {
  bool connected = false;
  final _port = TextEditingController(text: '9000');
  final _data = TextEditingController();
  final _message = TextEditingController();
  final _scroller = ScrollController();
  late ServerSocket server;
  late Socket conn;
  bool server_status = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    if(connected) {
      conn.close();
      conn.destroy();
      connected = false;
    }
    if (server_status) {
      server.close();
      server_status = false;
    }
  }

  Future<void> _run_server(int port) async {
    ServerSocket listener;
    try{
      listener = await ServerSocket.bind('0.0.0.0', port);
    }
    catch(err){
      _data.text = '$err';
      return;
    }
    server = listener;
    if (mounted) {
      setState(() {
        server_status = true;
      });
    }
    await for (Socket conn1 in server) {
      _data.text = '${_data.text}From: ${conn1.remoteAddress.address}:${conn1.remotePort}\n';
      if (connected) {
        _data.text = '${_data.text}close\n';
        conn1.add(utf8.encode('无法处理多连接\n'));
        conn1.close();
        continue;
      }
      connected = true;
      conn = conn1;
      //conn.add(utf8.encode("Hello client: ${conn.remoteAddress.address}\n"));
      if(mounted) {
        setState(() {
          connected = true;
          }
        );
      }
      try{
        conn.listen(
          (msg) {
            var message = utf8.decode(msg);
            print('Received message from client: $message\n');
            _data.text = '${_data.text}$message';
          },
          onDone: () {
            _data.text = '${_data.text}Connect stop\n';
            if(mounted) {
              setState(() {
                connected = false;
              });
            }
            conn.destroy();
          },
          onError: (err) {
            _data.text = '${_data.text}Connect error:$err\n';
            if(mounted) {
              setState(() {
                connected = false;
              }); 
            }
            conn.destroy();
          },
        );
      }
      catch(err){
         _data.text = '$err';
        return;
      }
      
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("服务器模式")),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            if (!server_status) Text('监听端口：'),
            if (!server_status) TextField(
              controller: _port,
              onChanged: (value) {
                  var val = int.tryParse(value);
                  if (val==null) {
                    _port.text='9000';
                  }
              },
            ),
            if (!server_status)
              TextButton(
                child: Text('开始监听'),
                onPressed: () {
                  _data.text = 'listen port:${_port.text}\n';
                  if(!server_status){
                    _run_server(int.parse(_port.text));
                  }
                },
              ),
            if (connected)
              TextField(
                controller: _message,
                maxLines: null, // 允许无限行
                keyboardType: TextInputType.multiline,
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  hintText: '此处输入信息',
                ),
              ),
            if (connected)
              TextButton(
                onPressed: () {
                  conn.add(utf8.encode('${_message.text}\n'));
                  _message.text='';
                },
                child: Text('发送'),
              ),
            TextField(
              controller: _data,
              scrollController: _scroller,
              readOnly: true,
              maxLines: 8,
              decoration: InputDecoration(
                border: UnderlineInputBorder(),
                hintText: '此处显示输出信息',
              ),
            ),
            TextButton(
              onPressed: (){
                try{
                  if (server_status) {
                    server.close();
                    //server.destroy();
                    server_status = false;
                  }
                }
                catch(err) {
                  _data.text = 'error: $err';
                }
                try{
                  if(connected) {
                    conn.close();
                    //conn.destroy();
                    connected = false;
                  }
                  
                }
                catch(err) {
                  _data.text = 'error: $err';
                }
                
                Navigator.pop(context);
              }, 
              child: Text('客户端模式'),
            ),
          ],
        ),
      ),
    );
  }
}
